package java_0220.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * 借助栈实现前序遍历
 */
public class Num144_PreOrderNonRecursion {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret=new ArrayList<>();
        if(root==null){
            return ret;
        }
        //双端队列
        Deque<TreeNode> stack=new ArrayDeque<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode cur=stack.pop();
            //先访问根节点
            ret.add(cur.val);
            //先压入右孩子
            if(cur.right!=null){
                stack.push(cur.right);
            }
            //再压入左孩子
            if(cur.left!=null){
                stack.push(cur.left);
            }
        }
        return ret;
    }
}

